#include "BufferCreator.h"

BufferCreator::BufferCreator()
{
}

BufferCreator::~BufferCreator()
{
	data.~vector();
}

void BufferCreator::Add(wstring name, wstring rule)
{
	data.push_back(make_pair(name, rule));
}

wchar_t* BufferCreator::ReturnName(size_t i)
{
	wchar_t* name = new wchar_t[data[i].first.length() + 1];
	wcscpy(name, data[i].first.c_str());
	
	return name;
}

wchar_t* BufferCreator::ReturnRule(size_t i)
{
	wchar_t* rule = new wchar_t[data[i].second.length() + 1];
	wcscpy(rule, data[i].second.c_str());

	return rule;
}

wchar_t* BufferCreator::ReturnBuffer(size_t i)
{
	wchar_t* temp = new wchar_t[data[i].second.length() + 1];
	wcscpy(temp, data[i].second.c_str());
	
	wstring res = L"0";
	size_t count = 0;

	for (wchar_t* rule = wcstok(temp, L";"); rule != NULL; rule = wcstok(NULL, L";"))
	{
		++count;

		res += wcslen(rule);
		res += rule;
	}
	res[0] = count;
	
	delete [] temp;
	temp = new wchar_t[res.length() + 1];
	wcscpy(temp, res.c_str());

	return temp;
}

size_t BufferCreator::Size()
{
	return data.size();
}

void BufferCreator::SaveToFile()
{
	if (!data.size())
		return;
	
	wofstream f("data.dat");
	for (size_t i = 0; i < data.size() - 1; ++i)
	{
		f << data[i].first << endl;
		f << data[i].second << endl;
	}
	f << data[data.size() - 1].first << endl;
	f << data[data.size() - 1].second;
	f.close();
}

void BufferCreator::LoadFromFile()
{
	data.clear();
	wifstream f("data.dat");
	
	if (!f)
		return; 

	while (!f.eof())
	{
		wstring name, rule;
		getline(f, name);
		getline(f, rule);
		data.push_back(make_pair(name, rule)); 
	}
	f.close();
}